#include "UdpServer.hpp"
#include <memory>
#include<cstdio>
#include<vector>

enum
{
    POPENERR = 1,
};


void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " port[1024+]\n"
    << endl;
}

bool safecheck(const string&cmd)
{
  vector<string>key_word={//哪些是危险的指令
      "rm",
      "mv",
      "cp",
      "kill",
      "sudo",
      "unlink",
      "uninstall",
      "yum",
      "top",
      "while"
  };
  for(auto &word:key_word)
  {
    auto pos=cmd.find(word);
    if(pos!=string::npos)return false;
  }
  return true;
}

string Handler(const string &info)
{
    //string buffer = "Server get a message:";
    string buffer = info;
    cout << buffer<<endl;
    return buffer;
}

string ExcuteCommand(const string &cmd)
{
    cout << "get a request cmd: " << cmd <<endl;
    if(!safecheck(cmd)){
      return "Badman";
    }
    // check(cmd);
    // FILE *popen(const char *command, const char *type);使用指令，并将指令结果返回
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
      perror("popen");
      exit(POPENERR);
    }
    string result;
    char buffer[4096];
    while (true)
    {
      char *ok=fgets(buffer,sizeof(buffer),fp);
      if(ok==nullptr)break;
      result+=buffer;
    }
    pclose(fp);
    return result;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
      Usage(argv[0]);
      exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UpdServer> svr(new UpdServer(port));
    svr->Init();
    svr->Run();
}